package com.meida.module.arc.provider.handler;

import cn.afterturn.easypoi.util.WebFilenameUtils;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.meida.common.base.entity.EntityMap;
import com.meida.common.base.utils.FlymeUtils;
import com.meida.common.mybatis.base.mapper.SuperMapper;
import com.meida.common.mybatis.query.CriteriaQuery;
import com.meida.common.mybatis.vo.JoinBean;
import com.meida.common.poi.MyWordExportUtil;
import com.meida.common.utils.ApiAssert;
import com.meida.module.arc.client.entity.ArcCategory;
import com.meida.module.arc.client.entity.ArcReport;
import com.meida.module.arc.client.entity.ArcUse;
import com.meida.module.arc.client.entity.ArcUseRecord;
import com.meida.module.arc.client.enums.ArchiveEnumInteger;
import com.meida.module.arc.client.enums.CategoryTypeEnum;
import com.meida.module.arc.client.enums.ReportTypeEnum;
import com.meida.module.arc.client.handler.ReportExportHandler;
import com.meida.module.arc.provider.service.*;
import com.meida.module.system.client.entity.SysDept;
import com.meida.module.system.provider.service.SysDeptService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <b>功能名：ArcInfoReportHandler</b><br>
 * <b>说明：</b><br>
 * <b>著作权：</b> Copyright (C) 2021 HUIFANEDU  CORPORATION<br>
 * <b>修改履历：
 *
 * @author 2022-01-07 jiabing
 */
@Slf4j
@Component("arcUseReportHandler")
public class ArcUseReportHandler implements ReportExportHandler {

    @Autowired
    private ArcReportService arcReportService;

    @Autowired
    private ArcUseRecordService arcUseRecordService ;

    @Autowired
    private SysDeptService sysDeptService;

    @Autowired
    private ArcCategoryService arcCategoryService;

    @Override
    public void export(Map params, HttpServletRequest request, HttpServletResponse response,String localTempPath,String exportName) {
        Object reportId = params.get("reportId");
        ApiAssert.isNotEmpty("报表id不能为空",reportId);
        Object useRecordIds = params.get("useRecordIds");
        ApiAssert.isNotEmpty("档案利用id不能为空",useRecordIds);
        Object qzId = params.get("qzId");
        ApiAssert.isNotEmpty("全宗id不能为空",qzId);
        ArcReport report = this.arcReportService.getById(Long.parseLong(reportId.toString()));

        String[] useRecordIdArr = useRecordIds.toString().split(",");
        if(FlymeUtils.isEmpty(useRecordIdArr)){
            ApiAssert.failure("档案利用id为空");
        }
        if(ArchiveEnumInteger.IS_TRUE.getCode().equals(report.getIsOne())&&useRecordIdArr.length>1){
            ApiAssert.failure("报表配置为单条数据，但是传了多个档案利用数据");
        }
        Map<String, Object> objInfo = new HashMap();
        List<Map> list = new ArrayList<>();
        for(int i=0;i<useRecordIdArr.length;i++){
            Map<String,Object> result = new HashMap<>();
            CriteriaQuery<ArcUseRecord> criteriaQuery = new CriteriaQuery<ArcUseRecord>(ArcUseRecord.class);

            JoinBean joinBean = criteriaQuery.createJoin(ArcUse.class);
            joinBean.setJoinField("useId");
            joinBean.setMainField("useId");

            criteriaQuery.eq(ArcUseRecord.class,"qzId",Long.parseLong(qzId.toString()));
            criteriaQuery.eq(ArcUseRecord.class,"useRecordId",Long.parseLong(useRecordIdArr[i].toString()));
            criteriaQuery.addSelect(ArcUse.class,"categoryId");
            criteriaQuery.addSelect(ArcUse.class,"archiveName");
            criteriaQuery.addSelect(ArcUse.class,"arcNo");
            criteriaQuery.addSelect(ArcUseRecord.class,"useUnitId");
            criteriaQuery.addSelect(ArcUseRecord.class,"useUserName");
            criteriaQuery.addSelect(ArcUseRecord.class,"usePhone");
            criteriaQuery.addSelect(ArcUseRecord.class,"useTime");
            criteriaQuery.addSelect(ArcUseRecord.class,"borrowDay");
            criteriaQuery.addSelect(ArcUseRecord.class,"isOriginal");
            criteriaQuery.addSelect(ArcUseRecord.class,"isPrint");
            criteriaQuery.addSelect(ArcUseRecord.class,"isDownload");
            criteriaQuery.addSelect(ArcUseRecord.class,"canDownloadCount");
            criteriaQuery.addSelect(ArcUseRecord.class,"downloadCount");
            List<EntityMap> resultList = arcUseRecordService.selectEntityMap(criteriaQuery);
            ApiAssert.isNotEmpty("档案利用记录为空",resultList);
            if(resultList.size()>1){
                log.error("档案利用导出，同一借阅id查询出多个结果 useRecordId="+useRecordIdArr[i]);
            }
//            Map<String,String> unitMap = new HashMap<>();
            if(resultList.size()>0){
                result.putAll(resultList.get(0));
                ArcCategory arcCategory = this.arcCategoryService.getById(Long.parseLong(result.get("categoryId").toString()));
                result.put("categoryName",arcCategory.getCnName());
                CategoryTypeEnum categoryTypeEnum = CategoryTypeEnum.getValue(arcCategory.getType());
                result.put("categoryType",categoryTypeEnum==null?"":categoryTypeEnum.getName());
                result.put("nowData", DateUtil.format(new Date(),"yyyy-MM-dd"));
                result.put("nowTime",DateUtil.format(new Date(),"HH:mm:ss"));
                result.put("useUnitId",result.get("useUnitId"));
//                if(FlymeUtils.isEmpty(unitMap)){
//                    QueryWrapper<SysDept> query = new QueryWrapper();
//                    query.lambda().eq(SysDept::getCompanyId,Long.parseLong(qzId.toString()));
//                    List<SysDept> deptList = this.sysDeptService.list(query);
//                    deptList.forEach(dept->{
//                        unitMap.put(dept.getDeptId().toString(),dept.getDeptName());
//                    });
//                }
//                if(FlymeUtils.isNotEmpty(unitMap.get(result.get("useUnitId").toString()))){
//                    result.put("useUnitId",unitMap.get(result.get("useUnitId").toString()));
//                }
            }

            if(i==0){
                objInfo.putAll(result);
            }
            list.add(result);
        }



        objInfo.put("list",list);
        try {
            response.setHeader("content-disposition", WebFilenameUtils.disposition(exportName));
            XWPFDocument doc = MyWordExportUtil.exportWord07(localTempPath, objInfo);
            ServletOutputStream out = response.getOutputStream();
            doc.write(out);
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}